package org.com.repair.service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.com.repair.DTO.NewUserRequest;
import org.com.repair.DTO.UserResponse;
import org.com.repair.entity.User;
import org.com.repair.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
    
    private final UserRepository userRepository;
    
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    
    @Transactional
    public UserResponse registerUser(NewUserRequest request) {
        if (userRepository.existsByUsername(request.username())) {
            throw new RuntimeException("用户名已存在");
        }
        
        User user = new User();
        user.setUsername(request.username());
        user.setPassword(request.password());
        user.setName(request.name());
        user.setPhone(request.phone());
        user.setEmail(request.email());
        user.setAddress(request.address());
        
        User savedUser = userRepository.save(user);
        return new UserResponse(savedUser);
    }
    
    public Optional<UserResponse> getUserById(Long id) {
        return userRepository.findById(id)
                .map(UserResponse::new);
    }
    
    public Optional<UserResponse> getUserByUsername(String username) {
        return userRepository.findByUsername(username)
                .map(UserResponse::new);
    }
    
    @Transactional
    public UserResponse updateUser(Long id, NewUserRequest request) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        user.setName(request.name());
        user.setPhone(request.phone());
        user.setEmail(request.email());
        user.setAddress(request.address());
        
        if (request.password() != null && !request.password().isEmpty()) {
            user.setPassword(request.password());
        }
        
        User updatedUser = userRepository.save(user);
        return new UserResponse(updatedUser);
    }
    
    @Transactional
    public boolean deleteUser(Long id) {
        if (userRepository.existsById(id)) {
            userRepository.deleteById(id);
            return true;
        }
        return false;
    }
    
    public List<UserResponse> getAllUsers() {
        return userRepository.findAll().stream()
                .map(UserResponse::new)
                .collect(Collectors.toList());
    }
    
    public Optional<UserResponse> login(String username, String password) {
        return userRepository.findByUsernameAndPassword(username, password)
                .map(UserResponse::new);
    }
} 